import moment from "moment-timezone";
import i18n from "@/i18n";
import { useStore } from "@/stores";
import {
	judgeIosPermissionRecord,
	judgeIosPermissionCamera,
	requestAndroidPermission,
} from "./permission";

import {
	GroupInfo,
	FriendInfoSelect,
	MessageReadReceipt,
} from "@/api/ImApi";

let isIos : boolean;
// #ifdef APP-PLUS
isIos = uni.getSystemInfoSync().platform == "ios";
// #endif
export function goTo(url : string, title : string = "") {
	uni.navigateTo({
		url,
		success: () => {
			if (title) {
				setTimeout(() => {
					uni.showToast({
						title,
						icon: "none",
					});
				});
			}
		},
	});
}
export function goToTab(url : string) {
	uni.switchTab({
		url: url,
	});
}
export function goBack(delta : number, title : string = "") {
	const canNavBack = getCurrentPages();
	if (canNavBack && canNavBack.length > 1) {
		uni.navigateBack({
			delta,
			success: () => {
				if (title) {
					setTimeout(() => {
						uni.showToast({
							title,
							icon: "none",
						});
					}, 100);
				}
			},
		});
	} else {
		uni.reLaunch({
			url: "/pages/index/index",
		});
	}
}
export function goReLaunch(url : string, title : string = "") {
	uni.reLaunch({
		url,
		success: () => {
			if (title) {
				setTimeout(() => {
					uni.showToast({
						title,
						icon: "none",
					});
				}, 100);
			}
		},
	});
}
export function goRedirectTo(url : string, title : string = "") {
	uni.redirectTo({
		url: url,
		success: () => {
			if (title) {
				setTimeout(() => {
					uni.showToast({
						title,
						icon: "none",
					});
				}, 100);
			}
		},
	});
}
export function copyText(data : string) {
	uni.setClipboardData({
		data,
		showToast: false,
		success: () => {
			uni.showToast({
				title: "复制成功",
				icon: "none",
			});
		},
	});
}
// 时间进制
export function formattingTime(time : string | number, type : number) : string {
	// 从 localStorage 中获取 UTC 偏移值，默认值为 0
	const utcOffsetMinutes = Number(uni.getStorageSync("utcOffsetMinutes") || 0);

	// 通用的格式化函数
	const formatTime = (time : moment.Moment, format : string) : string =>
		time.utc().utcOffset(utcOffsetMinutes).format(format);

	// 类型为 1，返回 "YYYY/MM/DD"
	if (type === 1) {
		return formatTime(moment(time), "YYYY/MM/DD");
	}

	// 类型为 2，聊天时间格式
	if (type === 2) {
		const currentDate = moment()
			.utc()
			.utcOffset(utcOffsetMinutes)
			.startOf("day"); // 当前日期（仅日期部分）
		const messageDate = moment(time)
			.utc()
			.utcOffset(utcOffsetMinutes)
			.startOf("day"); // 消息日期（仅日期部分）

		const diffDays = currentDate.diff(messageDate, "days"); // 当前日期与消息日期的天数差
		const hours = moment(time).utc().utcOffset(utcOffsetMinutes).hours(); // 小时
		const minutes = moment(time).utc().utcOffset(utcOffsetMinutes).minutes(); // 分钟（补零处理）
		const formattedMinutes = minutes < 10 ? `0${minutes}` : minutes;

		// 今天的消息
		if (diffDays === 0) {
			return `${hours}:${formattedMinutes}`; // 返回时和分
		}

		// 昨天的消息
		if (diffDays === 1) {
			return `昨天${hours}:${formattedMinutes}`;
		}

		// 最近一周的消息
		if (diffDays <= 7) {
			return `${diffDays}天前`;
		}

		// 更早的消息
		return formatTime(moment(time), "YYYY/MM/DD");
	}

	// 默认格式化返回 "YYYY/MM/DD HH:mm:ss"
	return formatTime(moment(time), "YYYY/MM/DD HH:mm:ss");
}

// 显示时间的函数
export function shouldShowTime(index : number, messagesList : any[]) : boolean {
	if (index === 0) return true; // 第一个消息显示时间

	// 获取当前消息和下一条消息的索引
	const currentMessage = messagesList[index];
	const nextMessage = messagesList[index + 1]; // 倒序时的上一条消息

	// 确保当前消息和下一条消息存在，并有 Time 属性
	if (!currentMessage?.Time || !nextMessage?.Time) {
		return false; // 如果任意一条消息没有时间，直接返回 false
	}

	// 计算时间差（毫秒）并转换为分钟
	const timeDifference = (currentMessage.Time - nextMessage.Time) / (1000 * 60);

	return timeDifference >= 5; // 如果相差 5 分钟以上，返回 true
}

// 深copy
export function deepClone(obj : any) : any {
	if (obj === null || typeof obj !== "object") return obj;
	if (Array.isArray(obj)) return obj.map((item) => deepClone(item));
	const newObj : any = {};
	Object.keys(obj).forEach((key) => {
		newObj[key] = deepClone(obj[key]);
	});
	return newObj;
}

// 获取图片宽高，添加重试机制
export async function getImageDimensions(
	url : string,
	retryCount = 0
) : Promise<{ width : number; height : number }> {
	return new Promise((resolve, reject) => {
		uni.getImageInfo({
			src: url,
			success: async (res) => {
				let { width, height } = await getmaxSize(res);
				resolve({
					width: Math.round(width),
					height: Math.round(height),
				});
			},
			fail: async () => {
				if (retryCount < 100) {
					// 如果重试次数小于 10 次，则等待 1 秒后重试
					console.log(`第 ${retryCount + 1} 次重试获取图片尺寸: ${url}`);
					await new Promise((resolve) => setTimeout(resolve, 1000)); // 等待 1 秒
					resolve(await getImageDimensions(url, retryCount + 1)); // 递归调用，增加重试次数
				} else {
					// 如果重试 10 次仍然失败，返回默认的宽高
					resolve({
						width: 150,
						height: 150,
					});
				}
			},
		});
	});
}
// 控制最大尺寸
export function getmaxSize(obj : any) : any {
	const maxWidth = 300;
	const maxHeight = 300;
	let width = obj.width;
	let height = obj.height;
	// 先根据宽度进行缩放
	if (obj.width > maxWidth) {
		const scale = maxWidth / width;
		width = maxWidth;
		height = height * scale;
	}

	// 再根据高度进行缩放
	if (height > maxHeight) {
		const scale = maxHeight / height;
		height = maxHeight;
		width = width * scale;
	}
	return { width, height };
}

// 转换视频时长
export function getVideoDuration(Time : any) : any {
	if (!Time) {
		return;
	}
	return (
		moment.duration(Time, "seconds").minutes() +
		":" +
		moment.duration(Time, "seconds").seconds().toString().padStart(2, "0")
	);
}

// 判断类型
export function typeCopywriting(item : any) : string {
	let text = "";
	let myUserInfo = uni.getStorageSync("userInfo");
	if (item.Grade == 2) {
		return item.Content?.Text;
	}
	switch (item.Cmd) {
		case 2:
			text = "[图片]";
			break;
		case 3:
			text = "[视频]";
			break;
		case 4:
			text = "[语音] " + item.Content?.Time + '"';
			break;
		case 5:
			text = "[文件] " + item.Content?.FileName;
			break;
		case 6:
			text = "[红包]";
			break;
		case 7:
			text = item.Content.call_type == 2 ? `[视频通话]` : "[语音通话]";
			break;
		case 8:
			text = item.Content.call_type == 2 ? `[视频通话]` : "[语音通话]";
			break;
		default:
			text = item.Content?.Text || "";
	}

	return item.Type == 2 && myUserInfo.user_id != item.Sender.user_id
		? (item.Sender.nick_name ? item.Sender.nick_name + "：" : "") + text
		: "" + text;
}
// 获取文件扩展显示图片
export function getImageSrc(fileName : string) : string {
	// 获取文件扩展名
	const fileType = fileName?.split(".").pop()?.toLowerCase() || "other";

	// 允许的文件扩展名列表
	const allowedTypes = [
		"txt",
		"pdf",
		"ppt",
		"doc",
		"docx",
		"xls",
		"xlsx",
		"zip",
		"7z",
		"rar",
	];

	const validFileType = allowedTypes.includes(fileType) ? fileType : "other";

	return `/static/image/document/${validFileType}.png`;
}

/**
 * 将字节转换为适当的单位（KB, MB, GB, etc.）
 * @param bytes 字节数
 * @param decimals 保留的小数位数，默认为 1
 * @returns 转换后的字符串
 */
export const formatBytes = (bytes : number, decimals : number = 1) : string => {
	if (bytes === 0) return "0 Bytes"; // 处理 0 字节的情况

	const k = 1024; // 一千零二十四字节为一 KB
	const dm = decimals < 0 ? 0 : decimals; // 保证小数位不小于 0
	const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]; // 可扩展单位

	// 计算单位索引
	const i = Math.floor(Math.log(bytes) / Math.log(k));

	// 返回格式化后的结果，保留指定小数位
	return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + sizes[i];
};
// 下载文件
export function handleDownload(url : string) : void {
	/*#ifdef APP-PLUS*/
	openExternalBrowser(url);
	/*#endif*/
	/*#ifdef H5*/
	window.location.href = url;
	/*#endif*/
}

// 打开外部浏览器
const openExternalBrowser = function (url : string) {
	// 判断平台
	const platform = uni.getSystemInfoSync().platform;
	if (platform === "android") {
		// 在Android平台上使用外部浏览器
		plus.runtime.openURL(url, function (error : any) {
			console.error("打开外部浏览器出错: " + error.message);
		});
	} else if (platform === "ios") {
		// 在iOS平台上使用外部浏览器
		plus.runtime.openWeb(url);
	} else {
		// 其他平台可能不支持直接打开外部浏览器，可以尝试使用 uni.navigateTo
		uni.navigateTo({
			url: "/pages/chat/filePreview?attachmentUrl=" + encodeURIComponent(url),
		});
	}
};

// 存入chatList数据
export async function setChatList(obj : any, id : string | number) {
	console.log(obj)
	console.log(id)
	const store = useStore();
	let chatList = await store.db.loadData("chatList", {
		id,
	});
	let info : any = {};
	if (chatList.length) {
		info = chatList[0];
		if(id){
			obj['chatId'] = String(id)
		}

	} else {
		if (id) {
			obj['chatId'] = String(id)

		}
		if (obj.Type == 1) {

			info = await FriendInfoSelect({ user_id: id });

		} else if (obj.Type == 2) {
			info = await GroupInfo({ group_id: id });
			

		} else {
			return;
		}



	}
	
	console.log(info,'---info')
	
	
	let arr = [
		{
			...info,
			...obj,
		},
	];
	console.warn("覆盖并且添加", arr);
	await store.db.saveData("chatList", arr);
}

// 判断是否超过24小时
export const isExpiredFn = async (time : number) => {
	const utcOffsetMinutes = Number(uni.getStorageSync("utcOffsetMinutes") || 0);

	// 获取当前时间并应用时区偏移
	const momentTime = moment()
		.utc()
		.utcOffset(utcOffsetMinutes)
		.format("YYYY/MM/DD HH:mm:ss");

	// 将格式化后的时间转换为时间戳
	const currentTime = moment(momentTime, "YYYY/MM/DD HH:mm:ss").valueOf();

	// 比较是否超过24小时
	return currentTime - time > 1000 * 60 * 60 * 24;
};

// 获取字符串的后 4 个字符
export const getLastFourChars = (str : string) : string => {
	if (!str) {
		return "";
	}
	return str.length <= 4 ? str : str.slice(-4);
};

// 排序方法（支持动态字段）
export const reduceFn = <T>(
	arr : T[],
	keyField : keyof T,
	keyField2 : keyof T
) : Record<string, T[]> => {
	if (!Array.isArray(arr)) {
		throw new Error("The first argument must be an array.");
	}

	return arr.reduce((groups, item) => {
		const key = ((item[keyField] || item[keyField2]) as string)
			?.charAt(0)
			.toUpperCase(); // 按首字母分组
		if (!key) {
			throw new Error(
				`Invalid keyField value for item: ${JSON.stringify(item)}`
			);
		}

		if (!groups[key]) {
			groups[key] = [];
		}
		groups[key].push(item);
		return groups;
	}, {} as Record<string, T[]>);
};

// 本地首页聊天列表
export const getChatList = async () : Promise<any[]> => {
	const store = useStore();

	const messages = await store.db.loadData("chatList", {});

	return messages;
};
const myUserInfo = uni.getStorageSync("userInfo");

// 本地首页聊天列表未读消息数量
export const getChatListNumber = async () : Promise<any[]> => {
	const store = useStore();
	console.log('2222')

	// 获取聊天列表
	let messages = await store.db.loadData("chatList", {});
	console.log('222', messages)

	// 获取未读消息列表
	const unreadMessage = await store.db.loadData("unreadMessage", {});
	console.log('333', unreadMessage)

	// 首先处理 unreadMessage 中的消息，优先将未读消息添加到 messages 中
	for (const unread of unreadMessage) {
		// 查找是否已经存在该未读消息对应的 chatId
		const found = messages.find((e : any) =>
			(unread.GroupId == e.chatId && e.Type === 2) ||  // 群聊
			(unread.Sender == e.chatId && e.Type === 1)     // 单聊
		);
	
		if (!found) {
			let id = unread.Type === 2 ? unread.GroupId : unread.Sender

			const newMessage = {
				id,
				myUserId: myUserInfo.user_id,
				unread: unread.MessageId,
				chatId: id,
				...unread,
			};
			await setChatList(
				{ ...newMessage, id },
				id
			);



		}
	}
	messages = await store.db.loadData("chatList", {});
	console.log('11-', messages)
	// 处理 messages 中的聊天记录
	for (const e of messages) {
		// 设置操作选项

		// 根据消息类型获取 chatId
		const type = e.Type === 2 ? "groupChat" : "singleChat";

		if (e.chatId) {
			console.log(e.chatId)
			console.log(typeof e.chatId)
			// 获取本地聊天记录，按条件过滤未读消息
			const list = await store.db.loadData(type, {
				chatId: e.chatId,
				unread: 0, // 只查询已读的最后一条数据
				Grade: 1,
				page: 1,
				limit: 1,
				Cmd: { $ne: 7 }, // 排除指定命令
			});
			console.log('只查询已读的最后一条数据--', list)

			// 查找最新的未读消息
			const latestUnread = unreadMessage.find(
				(msg : any) =>
					(msg.GroupId == e.chatId && e.Type === 2) || // 群聊
					(msg.Sender == e.chatId && e.Type === 1)    // 单聊
			);
			console.log('latestUnread--', latestUnread)

			if (latestUnread) {
				// 获取最新未读消息的 MessageId
				const latestMessageId = latestUnread.MessageId;
				e["MessageId"] = latestMessageId; // 更新最新未读消息的 MessageId

				// 获取本地消息中的 MessageId，如果没有则默认 0
				const localMessageId = list[0]?.MessageId || 0;

				// 计算未读消息数量
				const unreadCount = Math.max(latestMessageId - localMessageId, 0);


				// 更新当前聊天记录的未读消息数量
				e["unread"] = unreadCount;
			} else {
				// 如果没有找到未读消息，未读数量为 0
				e["unread"] = 0;
			}
		}
	}

	return messages;
};






// 获取总数量
export const getUnreadCount = async () : Promise<any[]> => {
	let chatList = [];

	chatList = await getChatListNumber();

	console.log(chatList, '获取总数量')


	const totalUnread = chatList.reduce(
		(sum : any, chat : any) => sum + chat.unread,
		0
	);
	console.log(totalUnread)

	// 设置 tabBar 未读数
	if (totalUnread) {
		uni.setTabBarBadge({
			index: 0,
			text: totalUnread > 99 ? "99+" : totalUnread.toString(),
		});
	} else {
		try {
			uni.removeTabBarBadge({
				index: 0,
			});
		} catch (error) { }
	}

	return chatList || [];
};

// 删除数据
export const deletingData = async (item : any) => {
	const store = useStore();

	await store.db.deleteData("chatList", { chatId: item.chatId });
	let baseDataType = item.GroupId ? "groupChat" : "singleChat";
	await store.db.deleteData(baseDataType, { chatId: item.chatId });

	// 获取未读消息列表
	let key = item.GroupId ? item.GroupId : item.SessionId;
	await store.db.deleteData("unreadMessage", { id: Number(item.chatId) });
	await MessageReadReceipt({
		key,
	});


	uni.showToast({ title: "记录删除成功", icon: 'none' })

};

// 跳转音视频
export const handleCall = async (call_type : number, friendInfo : any, isCaller : number = 0) => {
	/*#ifdef APP-PLUS*/
	if (isIos) {
		await judgeIosPermissionRecord();
		if (call_type == 2) {
			await judgeIosPermissionCamera();
		}
	} else {
		await requestAndroidPermission("android.permission.RECORD_AUDIO");
		if (call_type == 2) {
			await requestAndroidPermission("android.permission.CAMERA");
		}
	}
	/*#endif*/
	let myUserInfo = uni.getStorageSync("userInfo");
	let obj = {
		isCaller,
		call_type,
		friendInfo,
	};
	uni.navigateTo({
		url: `/pages/rtc/index?obj=${JSON.stringify(obj)}`,
	});
};

let innerAudioContext : any = null;

// 播放语音
export const playVoice = async (type : number, voicePath : string = "") => {
	innerAudioContext = uni.createInnerAudioContext();
	innerAudioContext.loop = false;
	if (isIos ) {
		innerAudioContext.volume = 0; // 初始静音
	} else {
		innerAudioContext.autoplay = true;
	}

	// 根据音频类型选择不同的音频文件
	switch (type) {
		case 1:
			innerAudioContext.loop = true; // 来电提示音设置为循环播放
			innerAudioContext.src = "/static/mp3/call.mp3";
			break;
		case 2:
			innerAudioContext.src = "/static/mp3/send.mp3"; // 发送语音提示音
			break;
		case 3:
			innerAudioContext.src = "/static/mp3/new.mp3"; // 新消息提示音
			break;
		default:
			innerAudioContext.src = voicePath; // 其他类型自定义路径
			break;
	}

	console.log("播放音频---", type);

	// 添加错误处理
	innerAudioContext.onError((err:any) => {
		console.error("音频播放出错", err);
	});

	// 可以根据需要添加播放结束后的操作
	innerAudioContext.onEnded(() => {
		console.log("音频播放结束");
		// 如果有其他操作可以在这里处理
	});

	// 监听音频加载完成
	innerAudioContext.onCanplay(() => {
		console.log("音频加载完成");
		// 播放音频
 // innerAudioContext.volume = 1; // 恢复音量
		innerAudioContext.play();
	});
};

// 暂停语音
export const pauseVoice = async () => {
	console.log("暂停语音---");
	innerAudioContext?.pause();
};
// 关闭语音
export const stopVoice = async () => {
	console.log("关闭音频---");
	innerAudioContext?.stop();
};